<template>
  <div class="app-container">
    <el-breadcrumb separator="/" style="margin-bottom: 20px" v-if="$route.query.merchant_name">
      <el-breadcrumb-item :to="{ path: '/merchant/list' }">机构清单</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $route.query.merchant_name }}</el-breadcrumb-item>
      <el-breadcrumb-item>管理员账号</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="handleAdd" size="small">
          添加管理员
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="所属机构：">
            <el-select v-model="listQuery.merchant_id" placeholder="请选择机构" clearable>
              <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名：">
            <el-input v-model="listQuery.username" class="input-width" placeholder="用户名"></el-input>
          </el-form-item>
          <el-button type="primary" size="small" @click="handleSearchList()">查询</el-button>
        </el-form>
      </div>
    </el-card>
    <div class="table-container">
      <el-table ref="adminTable" :data="list" style="width: 100%;" v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="所属机构" align="center">
          <template slot-scope="scope">{{ scope.row.merchant ? scope.row.merchant.name : '-' }}</template>
        </el-table-column>
        <el-table-column label="用户名" align="center">
          <template slot-scope="scope">{{ scope.row.username }}</template>
        </el-table-column>
        <el-table-column label="昵称" align="center">
          <template slot-scope="scope">{{ scope.row.nick_name }}</template>
        </el-table-column>
        <el-table-column label="邮箱" align="center">
          <template slot-scope="scope">{{ scope.row.email }}</template>
        </el-table-column>
        <el-table-column label="最后登录时间" align="center" width="180">
          <template slot-scope="scope">{{ formatDate(scope.row.login_time) }}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch @change="handleStatusChange(scope.$index, scope.row)" :active-value="1" :inactive-value="0"
              v-model="scope.row.status">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleUpdate(scope.$index, scope.row)">编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container" style="margin-bottom: 30px;">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :page-size="listQuery.pageSize" :page-sizes="[5, 10, 15]"
        :current-page.sync="listQuery.pageNum" :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog title="管理员账号" :visible.sync="dialogVisible" width="400px">
      <el-form :model="admin" :rules="rules" ref="adminForm" label-width="120px">
        <el-form-item label="所属机构：" prop="merchant_id">
          <el-select v-model="admin.merchant_id" placeholder="请选择机构" style="width: 100%" :disabled="isEdit">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员账号：" prop="username">
          <el-input v-model="admin.username" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码：" prop="password">
          <el-input v-model="admin.password" type="password" :placeholder="isEdit ? '不修改请留空' : '请输入密码'"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" :disabled="submitLoading">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '保存' : '添加' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList as fetchMerchantList, fetchAdminList, createAdmin, updateAdmin, deleteAdmin, updateAdminStatus } from '@/api/merchant'

export default {
  name: 'merchantAdminList',
  data() {
    return {
      listQuery: {
        merchant_id: null,
        username: null,
        pageNum: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      listLoading: false,
      submitLoading: false,
      merchantList: [],
      dialogVisible: false,
      dialogTitle: '添加管理员',
      isEdit: false,
      admin: {
        merchant_id: null,
        username: '',
        password: '',
        nick_name: '',
        email: '',
        note: ''
      },
      rules: {
        merchant_id: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' },
          { max: 255, message: '用户名长度不能超过255位', trigger: 'blur' }
        ],
        password: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getMerchantList()
    // 如果URL中有merchant_id参数，自动筛选该机构的管理员
    if (this.$route.query.merchant_id) {
      this.listQuery.merchant_id = parseInt(this.$route.query.merchant_id)
    }
    this.getList()
  },
  methods: {
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      if (isNaN(date.getTime())) return dateString

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    getMerchantList() {
      fetchMerchantList({ pageSize: 100 }).then(response => {
        this.merchantList = response.data.data
      })
    },
    getList() {
      this.listLoading = true
      fetchAdminList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.data
        this.total = response.data.total
      })
    },
    handleSearchList() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleResetSearch() {
      this.listQuery = {
        merchant_id: null,
        username: null,
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleStatusChange(index, row) {
      const oldStatus = row.status === 1 ? 0 : 1
      this.$confirm('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateAdminStatus(row.id, { status: row.status }).then(() => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.getList()
        }).catch(() => {
          row.status = oldStatus
        })
      }).catch(() => {
        // 取消时恢复原状态
        row.status = oldStatus
      })
    },
    handleDelete(index, row) {
      this.$confirm('是否要删除该管理员?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdmin(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      })
    },
    handleAdd() {
      this.dialogTitle = '添加管理员'
      this.isEdit = false
      // 优先使用筛选框中选择的机构ID，其次使用URL参数中的机构ID
      const merchantId = this.listQuery.merchant_id || (this.$route.query.merchant_id ? parseInt(this.$route.query.merchant_id) : null)
      this.admin = {
        merchant_id: merchantId,
        username: '',
        password: '',
        nick_name: '',
        email: '',
        note: ''
      }
      this.dialogVisible = true
    },
    handleUpdate(index, row) {
      this.dialogTitle = '编辑管理员'
      this.isEdit = true
      this.admin = Object.assign({}, row)
      this.dialogVisible = true
    },
    handleSubmit() {
      // 新增时验证密码必填
      if (!this.isEdit && !this.admin.password) {
        this.$message({
          type: 'warning',
          message: '请输入密码'
        })
        return
      }

      this.$refs.adminForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          if (this.isEdit) {
            // 编辑时，如果密码为空则不传递密码字段
            const updateData = { ...this.admin }
            if (!updateData.password) {
              delete updateData.password
            }
            updateAdmin(this.admin.id, updateData).then(response => {
              this.submitLoading = false
              this.$message({
                type: 'success',
                message: '更新成功!'
              })
              this.dialogVisible = false
              this.getList()
            }).catch(error => {
              this.submitLoading = false
              const errorMsg = (error.response && error.response.data && error.response.data.message) || error.message || '更新失败'
              this.$message({
                type: 'error',
                message: errorMsg
              })
            })
          } else {
            createAdmin(this.admin).then(response => {
              this.submitLoading = false
              this.$message({
                type: 'success',
                message: '创建成功!'
              })
              this.dialogVisible = false
              this.getList()
            }).catch(error => {
              this.submitLoading = false
              const errorMsg = (error.response && error.response.data && error.response.data.message) || error.message || '创建失败'
              this.$message({
                type: 'error',
                message: errorMsg
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.input-width {
  width: 203px;
}
</style>
